package com.xqboss.apps.service.consumer;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xqboss.apps.constant.RedisKey;
import com.xqboss.apps.domain.consumer.ConsumerTeamGiveRecord;
import com.xqboss.apps.dto.consumer.ConsumerGiftQueryDto;
import com.xqboss.apps.dto.consumer.ConsumerTeamGiveRecordDto;
import com.xqboss.apps.enums.consumer.ConsumerGiftTypeEnum;
import com.xqboss.apps.mapper.consumer.ConsumerTeamGiveRecordMapper;
import com.xqboss.apps.vo.consumer.ConsumerGiftRecordVo;
import com.xqboss.apps.vo.user.ConsumerTeamGiveRecordVo;
import com.xqboss.common.core.domain.PageList;
import com.xqboss.common.core.domain.entity.SysUser;
import com.xqboss.common.core.redis.RedisCache;
import com.xqboss.common.exception.ServiceException;
import com.xqboss.common.utils.StringUtils;
import com.xqboss.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 队伍转增（藏品/宝盒/装备）记录(ConsumerTeamGiveRecord)表服务接口
 *
 * @author makejava
 * @since 2023-12-15 14:27:09
 */
@Service
public class ConsumerTeamGiveRecordService extends ServiceImpl<ConsumerTeamGiveRecordMapper, ConsumerTeamGiveRecord> {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedisCache redisCache;


    /**
     * 转增记录
     *
     * @param dto 请求对象
     * @return ConsumerTeamGiveRecords
     */
    public List<ConsumerTeamGiveRecord> giveRecord(ConsumerTeamGiveRecordDto dto) {
        return null;
    }

    /**
     * 转增记录vo
     *
     * @param records records
     * @return vos
     */
    public List<ConsumerTeamGiveRecordVo> giveRecord(List<ConsumerTeamGiveRecord> records) {
        return null;
    }

    /**
     * 统计队伍中互送礼物数
     *
     * @param teamId 队伍id
     * @return
     */
    public Long countGift(Long teamId) {
        if (teamId==null) {
            throw new ServiceException("队伍id不能为空！");
        }
        return this.lambdaQuery().select(ConsumerTeamGiveRecord::getId).eq(ConsumerTeamGiveRecord::getTeamId, teamId).count();
    }

    /**
     * 礼物列表
     * @param param
     * @return
     */
    public PageList<ConsumerGiftRecordVo> giftList(ConsumerGiftQueryDto param) {
        int pageSize = param.getPageSize();
        int pageNum = param.getPageNum();
        param.setPageNum(null);
        param.setPageSize(null);
        List<ConsumerGiftRecordVo> list = baseMapper.giftList(param);
        if (!list.isEmpty()) {
            int offset = (pageNum - 1) * pageSize;
            // 手动分页
            List<ConsumerGiftRecordVo> result;
            if (param.getId() != null) {
                result = list.stream()
                        .filter(t -> t.getId().equals(param.getId()))
                        .collect(Collectors.toList());
            } else if (param.getIsComplete() != null) {
                List<ConsumerGiftRecordVo> result2 = list.stream()
                        .filter(t -> t.getIsComplete() == param.getIsComplete())
                        .collect(Collectors.toList());
                result = result2.subList(offset, Math.min(offset + pageSize, result2.size()));
            } else {
                result = list.subList(offset, Math.min(offset + pageSize, list.size()));
            }
            //  赠品类型和备注设置
            result.forEach(t -> {
                if (t.getGiveUserId() == null) {
                    t.setGiftType(ConsumerGiftTypeEnum.AIRDROP);
                    t.setAirdropId(t.getId());
                    t.setTargetName("加油蛙官方");
                    t.setTargetNum(list.stream().filter(y -> y.getGiveUserId() == null && y.getId() <= t.getId()).count());
                    t.setRemark(StringUtils.format("{}给你送来第{}个礼物",
                            t.getTargetName(),
                            t.getTargetNum()
                    ));
                } else if (t.getGiveUserId().equals(param.getUserId())) {
                    SysUser receiveUser = sysUserService.selectUserById(t.getReceiveUserId());
                    t.setGiftType(ConsumerGiftTypeEnum.SEND);
                    t.setTargetName(receiveUser != null ? receiveUser.getNickName() : "未知用户");
                    t.setTargetNum(list.stream().filter(y -> param.getUserId().equals(y.getGiveUserId()) && y.getId() <= t.getId()
                            && t.getReceiveUserId().equals(y.getReceiveUserId()))
                            .count());
                    t.setRemark(StringUtils.format("您向{}送了第{}个礼物",
                            t.getTargetName(),
                            t.getTargetNum()
                    ));
                } else {
                    SysUser giveUser = sysUserService.selectUserById(t.getGiveUserId());
                    t.setGiftType(ConsumerGiftTypeEnum.RECEIVE);
                    t.setTargetName(giveUser != null ? giveUser.getNickName() : "未知用户");
                    t.setTargetNum(list.stream().filter(y -> param.getUserId().equals(y.getReceiveUserId()) && y.getGiveUserId() != null
                                    && y.getId() <= t.getId() && t.getGiveUserId().equals(y.getGiveUserId()))
                            .count());
                    t.setRemark(StringUtils.format("{}给你送来了第{}个礼物",
                            t.getTargetName(),
                            t.getTargetNum()
                    ));
                }
            });
            // 清理未读缓存
            redisCache.deleteObject(RedisKey.KEY_USER_UNREAD_GIFT + param.getUserId());
            return new PageList<>(result, list.size());
        }
        return new PageList<>(list, list.size());
    }

    /**
     * 统计用户转赠藏品的总数量
     * @param userId
     * @param type
     * @return
     */
    public int countByTransfer(Long userId, Long nftId, Integer type) {
        return baseMapper.countByTransfer(userId, nftId, type);
    }
}

